Modern API Development with Spring and Spring Boot by Sourabh Sharma

Modern API Development with Spring and Spring Boot by Sourabh Sharma

Author:Sourabh Sharma [Sourabh Sharma]
Language: eng
Format: epub
Publisher: Packt Publishing
Published: 2021-06-24T16:00:00+00:00


Developing the ProductDetail component

The ProductDetail component is similar to the ProductCard component, except that it loads the product details from the backend by using the ID from the path.

Let's see how this is done. Only code related to the Fetch product has been shown in the following snippet. The rest of the code is the same as for the ProductCard component. However, you can refer to the full code in the GitHub repository:

import { Link, useParams, useHistory } from "react-router-dom";

import ProductClient from "../api/ProductClient";

// Other imports removed for brevity

const ProductDetail = ({ auth }) => {

const { id } = useParams();

// Other declaration removed for brevity

// Other functions removed for brevity

useEffect(() => {

async function getProduct(id) {

const client = new ProductClient();

const res = await client.fetch(id);

if (res && res.success) {

setProduct(res.data);

}

}

// rest of code removed from brevity

getProduct(id);

}, [id]);

return ( /* JSX Template */ );

};

export default ProductDetail;

https://github.com/PacktPublishing/Modern-API-Development-with-Spring-and-Spring-Boot/blob/main/Chapter07/ecomm-ui/src/components/ProductDetail.js

You have used useParams() from the react-router-dom package to retrieve the product ID passed from the ProductCard component. This id property is then used to fetch the product from the backend server using the ProductClient component. Upon a successful response, the retrieved product detail is set in the state product using the setProduct state function.

We are done with the development of product-based components such as ProductList, Products, ProductCard, and ProductDetail. We will now focus on authentication functionality so that we can later work on the cart and orders components, which require an authenticated user.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.